﻿/*!
 * jQuery BTT Plugin
 * author: Evan Qiu@infosys.com
 * version: 1.00 (07-Aug-2013)
 * @requires jQuery v1.3.2 or later
 *
 * BTT plugin is to imeplement function that back to top in page.
 *
 * Example: 
*	1. $.BTT();
*	2. $.BTT({
*		container: $("#container"),
*		rate: 0.5
*	});
*	3. $(c).BTT();
*	4. $(c).BTT({
*		container: $("#container"),
*		rate: 2
*	});
 *
 */
(function($) {
	// parent element with scroll bar
	var _container;
	// rate of scrolling up
	// _rate > 0, and scroll up slower with greater _rate
	var _rate = 1;
	
	// action of back to top
	function btt() {
		var goTop = setInterval( scrollMove, 10 * _rate );
		function scrollMove() {
			setScrollTop( getScrollTop() / 1.1 );
			if ( getScrollTop() < 1 ) {
				clearInterval( goTop );
			}
		}
	}
	
	// get offset of container with scroll, container also could be window.
	function getScrollTop() {
		return $(_container).scrollTop();
	}
	
	// set value of scroll offset
	function setScrollTop(value) {
		$(_container).scrollTop(value);
	}
	
	// initialize paramters
	function init(container, rate) {
		_container = typeof container === 'undefined' ? document : container;
		if ( !isNaN(rate) ) {
			_rate = rate;
		}
	}
	
	// bind action to the control
	function bindControl(container, c) {
		if ( typeof container === 'undefined' ) {
			$(window).bind("scroll", funBTT);
		} else {
			$(_container).bind("scroll", funBTT);
		}
		
		function funBTT() {
			var st = getScrollTop();
			var winh = window.height;
			(st > 0)? $(c).fadeIn(500): $(c).fadeOut(500);
			//for IE6 
			if (!window.XMLHttpRequest) {
				$(c).css("top", st + winh - 200);
			}
		};
		$(function() { funBTT(); });
	}
	
	// function to back to top of container
	$.BTT = function(param) {
		init(param.container, param.rate);
		btt();
	}
	
	// bind function that back to top of container when click to the control.
	$.fn.BTT = function(param) {
		init(param.container, param.rate);
		bindControl(param.container, this);
		$(this).click(function() {
			btt();
		});
	};
	
})(jQuery);

